package day012.IBatis;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.jdbc.SimpleJdbcTestUtils;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class DeptApp {
	public static void main(String[] args) throws Exception {
		SetUpDB();
        
		Reader reader = Resources.getResourceAsReader("day012/IBatis/sqlMapConfig.xml");
		SqlMapClient client = SqlMapClientBuilder.buildSqlMapClient(reader);
		
		Dept dept1 = new Dept();
		dept1.setDeptno(60);
		dept1.setDname("HRD");
		dept1.setLoc("강남");
		
		// mapper 에 등록한 id, parameter 객체
		client.insert("DEPT.add", dept1);
		
		// SELECT - namespace 를 사용하도록 설정했을 경우 : namespace.id
		// SELECT 의 결과가 한 개일 경우는 queryForObject 를 사용
		Dept dept2 = (Dept)client.queryForObject("DEPT.info", 20);
		System.out.println("dept2 : " + dept2 + "\n");
		
		// SELECT 의 결과가 여러 개일 경우 queryForList 를 사용
		List<Dept> deptList = client.queryForList("DEPT.infoAll");
		
		for(int i = 0; i < deptList.size(); i++) {
			System.out.println("deptList : " + deptList.get(i));
		}
	}

	private static void SetUpDB() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("net.sf.log4jdbc.DriverSpy");
		dataSource.setUrl("jdbc:log4jdbc:hsqldb:hsql://localhost/sampledb");
		dataSource.setUsername("sa");
		dataSource.setPassword("");
		dataSource.setDefaultAutoCommit(true);
		dataSource.setPoolPreparedStatements(true);
		        
        SimpleJdbcTestUtils.executeSqlScript(
        		new SimpleJdbcTemplate(dataSource), 
        		new ClassPathResource("day012/IBatis/sample_schema_hsql.sql"), 
        		true);
	}
}
